package StudyCode.summary.BufferAndChannel;

import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousFileChannel;
import java.nio.charset.Charset;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.concurrent.Future;

/**
 * 版权所有 科技与人文(www.tah1986.com)
 */
public class ReadFileUsingFutureAndAsynchronousFileChannel {
	public static void main(String[] args) {
		ByteBuffer buffer = ByteBuffer.allocate(100);
		String encoding = System.getProperty("file.encoding");
		Path path = Paths.get("E:\\Copy", "1.txt");
		try (AsynchronousFileChannel asynchronousFileChannel = AsynchronousFileChannel
				.open(path, StandardOpenOption.READ)) {
			Future<Integer> result = asynchronousFileChannel.read(buffer, 0);
			while (!result.isDone()) {
				System.out.println("读取时可以做其它事 ...");
			}
			System.out.println("读取结束: " + result.isDone());
			System.out.println("读取的 Bytes: " + result.get());
		} catch (Exception ex) {
			System.err.println(ex);
		}
		buffer.flip();
		System.out.print(Charset.forName(encoding).decode(buffer));
		buffer.clear();
	}
}
